// yield暂停生成器
function* foo() {
  console.log('foo');
  const res = yield 'foo';
  console.log(res);
}

const generator = foo();

generator.next('bar');
generator.next('bar');

function ajax(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(this.statusText);
      }
    };
    xhr.send();
  });
}

function* main() {
  const person = yield ajax('/api/cuvee.json');
  console.log(person);
  const detail = yield ajax('/api/info.json');
  console.log(detail);
}

// const generator1 = main();
// generator1.next().value.then(person => {
//   // 指针
//   const pointer = generator1.next(person);
//   if (pointer.done) return;
//   pointer.value.then(detail => {
//     const pointer = generator1.next(detail);
//     if (pointer.done) return;
//     pointer.value.then(res => {
//       //
//     });
//   });
// });

function co(generator) {
  const generatorFn = generator();
  function generate(val) {
    const pointer = generatorFn.next(val);
    if (pointer.done) return;
    pointer.value.then(
      res => {
        return generate(res);
      },
      e => {
        generatorFn.throw(e);
      }
    );
  }
  generate();
}

co(main);
